package com.example.lwx;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class SqlActivity extends Activity implements View.OnClickListener {
    EditText et_name,et_pwd;
    Button btn_save,btn_read;
    private TextView tv;

    private MyHelper myHelper;
    private SQLiteDatabase database;
    private ContentValues vc;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shared);
        btn_read=findViewById(R.id.readinfo);
        btn_save=findViewById(R.id.regist);
        et_name=findViewById(R.id.edname);
        et_pwd=findViewById(R.id.edpassword);
        tv=findViewById(R.id.info);
        myHelper=new MyHelper(SqlActivity.this);
        btn_read.setOnClickListener(this);
        btn_save.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.regist) {
            database = myHelper.getWritableDatabase();
            vc = new ContentValues();
            vc.put("name", et_name.getText().toString());
            vc.put("pwd", et_pwd.getText().toString());
            database.insert("user", null, vc);
            database.close();
        }
        if(view.getId()==R.id.readinfo){
            database = myHelper.getWritableDatabase();
            Cursor cursor=database.query("user",null,null,null,null,null,null);
            if(cursor.getCount()==0){
                Toast.makeText(SqlActivity.this,"查询结果为空",Toast.LENGTH_SHORT).show();

            }else{
                if(cursor.moveToFirst()){
                    String name=cursor.getString(1);
                    String password=cursor.getString(2);
                    tv.setText("账号"+name+"密码"+password+"\n");
                }
                while(cursor.moveToNext()){
                    String name=cursor.getString(1);
                    String password=cursor.getString(2);
                    tv.setText("账号"+name+"密码"+password+"\n");
                }
                cursor.close();
            }
        database.close();
        }
    }
}
